package cn.tedu._05weibo.controller;

import cn.tedu._05weibo.base.response.JsonResult;
import cn.tedu._05weibo.base.response.StatusCode;
import cn.tedu._05weibo.mapper.WeiboMapper;
import cn.tedu._05weibo.pojo.dto.WeiboAddParam;
import cn.tedu._05weibo.pojo.entity.Weibo;
import cn.tedu._05weibo.pojo.vo.UserVO;
import cn.tedu._05weibo.pojo.vo.WeiboDetailVO;
import cn.tedu._05weibo.pojo.vo.WeiboIndexVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Validated
@RestController
@Api(tags = "02.微博模块")
@Slf4j
@RequestMapping("/v1/weibo/")
public class WeiboController {
    @Autowired
    private WeiboMapper weiboMapper;

    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;

    /**
     * 1.发布微博功能
     * @param weiboAddParam
     * @param session
     * @return
     */
    @PostMapping("insert")
    @ApiOperation("发布微博功能")
    @ApiOperationSupport(order = 10)
    public JsonResult insert(@RequestBody WeiboAddParam weiboAddParam, @ApiIgnore HttpSession session){
        /*
            1.校验登录状态;
            2.未登录状态: return 2;
            3.已登录状态: INSERT接口, 然后return 1;
         */
        log.debug("weiboAddParam:{}", weiboAddParam);
        UserVO userVO = (UserVO) session.getAttribute("user");
        /*
        if(userVO == null){
            return new JsonResult(StatusCode.NOT_LOGIN);
        }
        */

        Weibo weibo = new Weibo();
        BeanUtils.copyProperties(weiboAddParam, weibo);
        weibo.setCreateTime(new Date());
        weibo.setUserId(userVO.getId());
        weiboMapper.insertWeibo(weibo);
        return JsonResult.ok();
    }

    /**
     * 2.微博首页列表
     */
    @GetMapping("selectIndex")
    @ApiOperation("微博首页列表功能")
    @ApiOperationSupport(order = 20)
    public JsonResult selectIndex(){
         /*
            设计Redis中的key-value：{"weibo_index":'{"data":...}'}
            1.确认缓存[Redis]中是否存在响应数据 GET key；
            2.缓存中存在，直接返回结束；
            3.缓存中不存在
                3.1 到MySQL中查询响应数据；
                3.2 将响应的数据缓存到Redis中  SET key value；
                3.3 返回结束
         */

        ValueOperations<String, Serializable> ops = redisTemplate.opsForValue();
        Serializable index = ops.get("weibo_index");
        if(index != null){
            System.out.println("首页数据来自于Redis数据库...");

            return JsonResult.ok(index);
        }else {
            List<WeiboIndexVO> weiboIndexVOS = weiboMapper.selectIndex();

            ops.set("weibo_index",(Serializable) weiboIndexVOS,30, TimeUnit.SECONDS);

            System.out.println("首页数据来自于MySQL数据库...");
            return JsonResult.ok(weiboIndexVOS);
        }


    }

    /**
     * 3.微博详情功能
     */
    @ApiOperation("微博详情页功能")
    @GetMapping("selectById")
    @ApiImplicitParam(name = "id", value = "微博ID", required = true, dataType = "Long")
    public JsonResult selectById(@Range(min = 1, max = 100, message = "id必须在1-100之间") @RequestParam Long id){
        log.debug("id = " + id);
        WeiboDetailVO weiboDetailVO = weiboMapper.selectById(id);

        return JsonResult.ok(weiboDetailVO);
    }
}
